import axios from "axios";
import qs from 'qs';


/**
 * 处理错误信息
 */
const errorHandle  = (status,info) =>{
    switch(status){
        case 404 :
            console.log("语义错误,不能被服务器理解")
            break;
        default :
            console.log(info);
    }
}

const errorHandle1 = (code,info) =>{
    switch(code){
        default :
            console.log(info);
    }
}


/**
 * 创建实例对象
 */
const instance = axios.create({
    // 公共配置
    baseURL:"http://192.168.1.6:8080",
    timeout:50000
})

/**
 * 拦截器处理
 */
instance.interceptors.request.use(
    
    config =>{
        // debugger;
        config.headers.Authorization = sessionStorage.getItem('token');
        // if(config.method === 'post'){
        //     config.data = qs.stringify(config.data)
            
        // }
        // if(sessionStorage.getItem('token'))
        return config;
    },
    error => Promise.reject(error)
)

/**
 * 响应拦截
 */
instance.interceptors.response.use(
    //完成了
    response => response.status === 200 ? Promise.resolve(response) : Promise.reject(response),
    error =>{
        //
        const {response} = error;
        errorHandle(response.status,response.info);
    }
    
   
)


instance.interceptors.response.use(data =>{
        if(data != null){
            if(data.code !== 200){
                errorHandle1(data.code,data.message);
            }
            if(data.data.code === 201 ){
                window.location="/login"
            }
            
        }
        return data
       
}
)

export default instance